package com.zs.backend.modules.certificate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zs.backend.common.service.OSSService;
import com.zs.backend.common.utils.CollectionUtil;
import com.zs.backend.common.utils.DateUtils;
import com.zs.backend.modules.certificate.dto.UserCertificateDTO;
import com.zs.backend.modules.certificate.mapper.UserCertificateMapper;
import com.zs.backend.modules.certificate.model.UserCertificate;
import com.zs.backend.common.utils.BeanUtil;
import com.zs.backend.common.utils.StringUtil;
import com.zs.backend.common.UserHolder;
import com.zs.backend.modules.certificate.service.UserCertificateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zs.backend.modules.enterpriseOrder.dto.EnterpriseOrderDTO;
import com.zs.backend.modules.enterpriseOrder.model.EnterpriseOrder;
import com.zs.backend.modules.ums.model.UmsAdmin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 证书表 服务实现类
 * </p>
 *
 * @author zs
 * @since 2024-03-18
 */
@Service
public class UserCertificateServiceImpl
    extends ServiceImpl<UserCertificateMapper, UserCertificate> implements
    UserCertificateService {

    @Autowired
    private OSSService ossService;


    @Override
    public Page<UserCertificateDTO> list(UserCertificateDTO userCertificateDTO,
        Integer pageSize, Integer pageNum) {
        Page<UserCertificate> page = new Page<>(pageNum,pageSize);
        QueryWrapper<UserCertificate> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<UserCertificate> lambda = wrapper.lambda();
        lambda.likeRight(StringUtil.isNotEmpty(userCertificateDTO.getCompanyName()),
            UserCertificate::getCompanyName, userCertificateDTO.getCompanyName());

        lambda.likeRight(StringUtil.isNotEmpty(userCertificateDTO.getAcceptCertificateUserName()),
            UserCertificate::getAcceptCertificateUserName, userCertificateDTO.getAcceptCertificateUserName());
        lambda.likeRight(StringUtil.isNotEmpty(userCertificateDTO.getAcceptCertificateUserName()),
            UserCertificate::getAcceptCertificateUserName, userCertificateDTO.getAcceptCertificateUserName());
        lambda.likeRight(StringUtil.isNotEmpty(userCertificateDTO.getPersonnelName()),
            UserCertificate::getPersonnelName, userCertificateDTO.getPersonnelName());
        lambda.ge(userCertificateDTO.getStartGraduationTime() != null,
            UserCertificate::getGraduationTime, userCertificateDTO.getStartGraduationTime());
        lambda.le(userCertificateDTO.getEndGraduationTime() != null,
            UserCertificate::getGraduationTime, userCertificateDTO.getEndGraduationTime());
        lambda.likeRight(StringUtil.isNotEmpty(userCertificateDTO.getPersonnelTel()),
            UserCertificate::getPersonnelTel, userCertificateDTO.getPersonnelTel());
        lambda.eq(StringUtil.isNotEmpty(userCertificateDTO.getTitleMajor()),
            UserCertificate::getTitleMajor, userCertificateDTO.getTitleMajor());
        lambda.eq(StringUtil.isNotEmpty(userCertificateDTO.getCertificateTypeName()),
            UserCertificate::getCertificateTypeName, userCertificateDTO.getCertificateTypeName());
        lambda.eq(StringUtil.isNotEmpty(userCertificateDTO.getGraduationMajor()),
            UserCertificate::getGraduationMajor, userCertificateDTO.getGraduationMajor());
        lambda.ge(userCertificateDTO.getStartTitleTime() != null,
            UserCertificate::getTitleTime, userCertificateDTO.getStartTitleTime());
        lambda.le(userCertificateDTO.getEndTitleTime() != null,
            UserCertificate::getTitleTime, userCertificateDTO.getEndTitleTime());
        lambda.eq(StringUtil.isNotEmpty(userCertificateDTO.getCategory()),
            UserCertificate::getCategory, userCertificateDTO.getCategory());
        lambda.eq(StringUtil.isNotEmpty(userCertificateDTO.getQualification()),
            UserCertificate::getQualification, userCertificateDTO.getQualification());
        lambda.eq(userCertificateDTO.getType() != null,
            UserCertificate::getType, userCertificateDTO.getType());
        lambda.likeRight(StringUtil.isNotEmpty(userCertificateDTO.getIdCard()),
            UserCertificate::getIdCard, userCertificateDTO.getIdCard());
        lambda.likeRight(StringUtil.isNotEmpty(userCertificateDTO.getCertificateBelongingPlace()),
            UserCertificate::getCertificateBelongingPlace, userCertificateDTO.getCertificateBelongingPlace());
        lambda.eq(StringUtil.isNotEmpty(userCertificateDTO.getRestrictedAreas()),
            UserCertificate::getRestrictedAreas, userCertificateDTO.getRestrictedAreas());
        lambda.eq(StringUtil.isNotEmpty(userCertificateDTO.getRestrictedAreas()),
            UserCertificate::getRestrictedAreas, userCertificateDTO.getRestrictedAreas());
        lambda.likeRight(StringUtil.isNotEmpty(userCertificateDTO.getLikeTitleMajor()),
            UserCertificate::getTitleMajor, userCertificateDTO.getLikeTitleMajor());
        lambda.eq(StringUtil.isNotEmpty(userCertificateDTO.getTitleNumber()),
            UserCertificate::getTitleNumber, userCertificateDTO.getTitleNumber());
        lambda.ge(userCertificateDTO.getStartCreateTime() != null,
            UserCertificate::getCreateTime, userCertificateDTO.getStartCreateTime());
        lambda.lt(userCertificateDTO.getEndCreateTime() != null,
            UserCertificate::getCreateTime, DateUtils.daysOperation(userCertificateDTO.getEndCreateTime(), 1));
        lambda.likeRight(StringUtil.isNotEmpty(userCertificateDTO.getPlaceCode()),
            UserCertificate::getPlaceCode, userCertificateDTO.getPlaceCode());
        List<String> restrictedAreasList = new ArrayList<>();
        if(StringUtil.isNotEmpty(userCertificateDTO.getRestrictedAreass()) && userCertificateDTO.getRestrictedAreass().contains(",")){
            restrictedAreasList = Arrays.asList(userCertificateDTO.getRestrictedAreass().split(","));
        }

        lambda.in(CollectionUtil.isNotNullAndEmpty(restrictedAreasList), UserCertificate::getRestrictedAreas, restrictedAreasList);

        lambda.eq(UserCertificate::getStatus, 0);
        lambda.orderByDesc(UserCertificate::getUpdateTime);
        //return page(page,wrapper);

        Page<UserCertificate> pageList = page(page,wrapper);
        if(pageList == null){
            return new Page<>();
        }
        List<UserCertificateDTO> result = BeanUtil.beanCopyPropertiesForList(pageList.getRecords(), UserCertificateDTO.class);

        if(CollectionUtil.isNotNullAndEmpty(result)){

            for(UserCertificateDTO dto : result){
                if(StringUtil.isNotEmpty(dto.getPersonnelTel())){
                    dto.setEncodeTel(StringUtil.encryptPhoneNumber(dto.getPersonnelTel()));
                }
                if(StringUtil.isNotEmpty(dto.getIdCard())){
                    dto.setEncodeIdCard(StringUtil.encryptIdCardNumber(dto.getIdCard()));
                }
            }
        }
        Page<UserCertificateDTO> pageResult = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        pageResult.setRecords(result);
        return pageResult;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean addOrUpt(UserCertificateDTO request) {
        UmsAdmin umsAdmin = UserHolder.getCurrentAdmin();
        request.setCreateUid(umsAdmin.getId());
        request.setCreateUname(umsAdmin.getUsername());

        // 将上传的文件转化为二进制
        if(request.getCertificateFile() != null){
            //request.setCertificateData(getCertificateData(request));
            String fileName = request.getCertificateFile().getOriginalFilename();
            request.setCertificateDataName(fileName);
            request.setCertificateDataType(fileName.substring(fileName.lastIndexOf(".") + 1));
            String filePath = ossService.filePath(request.getCertificateFile());
            String fileUrl = ossService.upload(request.getCertificateFile(), filePath);
            request.setFileUrl(fileUrl);
            request.setFilePath(filePath);

        }
        UserCertificate userCertificate = BeanUtil.beanCopyProperties(request, UserCertificate.class);

        if(request.getId() != null){
            return updateById(userCertificate);
        }
        return save(userCertificate);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean updateDel(Long id) {
        UserCertificate userCertificate = getById(id);
        userCertificate.setStatus(1);
        // 删除文件
        ossService.deleteFile(userCertificate.getFilePath());
        return updateById(userCertificate);
    }

    @Override
    public UserCertificate getFileInfo(Long id) {
        QueryWrapper<UserCertificate> wrapper = new QueryWrapper<>();
        wrapper.select("id", "certificate_data", "certificate_data_name", "certificate_data_type");
        wrapper.eq("id", id);
        return this.getOne(wrapper);
    }



    private byte[] getCertificateData(UserCertificateDTO certificate){
        MultipartFile file = certificate.getCertificateFile();
        byte[] certificateData = null;
        if(file == null){
            return certificateData;
        }
        try {
            certificateData = file.getBytes();
            String fileName = file.getOriginalFilename();
            certificate.setCertificateDataName(fileName);
            certificate.setCertificateDataType(fileName.substring(fileName.lastIndexOf(".") + 1));
        }catch (Exception e){
            throw new RuntimeException("解析证书文件异常");
        }

        return certificateData;

    }


}
